
//  显示日期的总个数 6 * 7
var MAX_DATE_COUNT = 42;
var RAW_DATE_COUNT = 7;
var MAX_YEAR_COUNT = 15;
var RAW_YEAR_COUNT = 3;
var MAX_MONTH_COUNT = 12;
var RAW_MONTH_COUNT = 4;
var selectMonth, selectYear;
if(!selectYear || !selectMonth) {
  now = new Date();
  selectMonth = now.getMonth();
  selectYear = now.getFullYear();
}
// 构造函数
function MyDate(opt) {
  this.opt = opt;
  this.ele = document.querySelector('#' + opt.id);
  this.icon = document.createElement('i');
  this.dateDiv = document.createElement('div');
}  

var mydate = new MyDate({
  id: 'mydate',
  /** type: year month date time */
  type: 'time',   
});

init();

function init() {
  initEvent();
  addDom();
  renderContent();
}

function initEvent() {
  document.addEventListener('click', _onDocumentEvent, false);
  mydate.ele.addEventListener('click', _onfocus, false);
  mydate.dateDiv.addEventListener('click', _onDateEvent, false);
  /** 内部事件 */
  function _onDocumentEvent(e) {
    var dateDiv = mydate.dateDiv;

    if(dateDiv.style.display == 'block') {
      dateDiv.style.display = 'none'; 
    }
  }

  function _onfocus(e) {
    var rectObj = e.currentTarget.getClientRects()[0];
    var dateDiv = mydate.dateDiv;
    
    e.stopPropagation();

    dateDiv.style.top = rectObj.height + 5 + 'px';
    dateDiv.style.display = 'block'; 
  }

  function _onDateEvent(e) {
    var target = e.target;
    switch(mydate.opt.type) {
      case 'year':
        _yearEvent(e); 
        break;
      case 'month':
        _monthEvent(e);
        break;
      case 'time':
        _timeEvent(e);
        break;  
      case 'date':
      default:
        _dateEvent(e);    
        break;
    }
    _buttonGounpEvent(e);
  }
   // 按钮组事件
  function _buttonGounpEvent(e) {
    var className = e.target.className;

    if(className == 'date-clear') {
      mydate.ele.value = '';
    } else if(className == 'date-now') {
      var now = new Date();
      mydate.ele.value = now.getFullYear() + '-' + 
        (now.getMonth() + 1) + '-' + now.getDate();
    } else if(className == 'date-select') {
      var date = document.querySelector('.date-current').innerText;
      mydate.ele.value = selectYear + '-' + ( selectMonth + 1 ) + '-' + date
    } 
  } 
  /** 日期 */
  function _dateEvent(e) {
    var target = e.target,
        className = target.className;
    
    e.stopPropagation();
    if(className.indexOf("fa") >= 0) {
      var curName = className.split(' ')[1];

      switch(curName) {
        case 'fa-angle-double-left':
          selectYear--;
          break;
        case 'fa-angle-left':
          selectMonth--;
          break;      
        case 'fa-angle-double-right':
          selectYear++;
          break;      
        case 'fa-angle-right':
          selectMonth++;
          break;        
      }
      renderContent();
    } 
    
    if(target.nodeName.toLowerCase() == 'td') {
      var d = target.innerText;
      mydate.ele.value = selectYear + '-' + (selectMonth + 1) + '-' + d;
    }
  }

  function _yearEvent(e) {
    var target = e.target,
        className = target.className;

    if(className.indexOf('fa') >= 0 ) {
      e.stopPropagation();
      var curName = className.split(' ')[1];

      switch(curName) {
        case 'fa-angle-double-left':
          selectYear -= MAX_YEAR_COUNT;
          break;      
        case 'fa-angle-double-right':
          selectYear += MAX_YEAR_COUNT;
          break;          
      }
      renderContent();
    } 
    if(target.nodeName.toLowerCase() == 'td') {
      var d = target.innerText.slice(0, -1);
      mydate.ele.value = d;
    }
  }

  function _monthEvent(e) {
    var target = e.target,
        className = target.className;

    if(className.indexOf('fa') >= 0 ) {
      e.stopPropagation();
      var curName = className.split(' ')[1];

      switch(curName) {
        case 'fa-angle-double-left':
          selectYear-- ;
          break;      
        case 'fa-angle-double-right':
          selectYear++;
          break;          
      }
      renderContent();
    } 
    if(target.nodeName.toLowerCase() == 'td') {
      var d = target.innerText.slice(0, -1);
      mydate.ele.value = d;
    }
  }
  
  function _timeEvent(e) {

  }
}

function addDom() {
  addIcon();
  addDateDiv();
  function addIcon() {
    var p = mydate.ele.parentElement;
    var icon = mydate.icon;
    var objStyle = {
      position: 'relative',
      left: '-25px',
      top: '1px'
    };
    p.style.position = 'relative';
    icon.classList.add('fa', 'fa-calendar');
    setStyle(icon, objStyle);
    p.appendChild(icon);
  }
  
  function addDateDiv() {
    var dateDiv = mydate.dateDiv,
        style = {
          position: 'absolute',
          border: '1px solid #333',
          display: 'none'
        };
    setStyle(dateDiv, style);
    mydate.ele.parentElement.appendChild(dateDiv);
  }
}

function renderContent() {
  switch(mydate.opt.type) {
    case 'date': 
      _renderDate();
      break;
    case 'year':
      _renderYear();
      break;
    case 'month':
      _renderMonth(); 
      break;
    case 'time':
      _renderTime();
      break;  
    default: 
      _renderDate();
      break;
  }

  function _renderYear() {
    var title = (selectYear - 7) + '年 - ' + (selectYear  + 7) +'年';
    _rander(_getHead(title), _getBody(_getYearBody))
  }
  
  function _renderDate() {
    var dateDiv = mydate.dateDiv,
        title = selectYear + ' 年' + (selectMonth + 1)  + ' 月',    
        body = _getDateBody();

    _rander(_getHead(title), _getBody(body));
  }
  
  function _renderMonth() {
    var title = selectYear + '月',
        body = _getMonthBody();

    _rander(_getHead(title), _getBody(body));
  }

  function _renderTime() {
    var title = '选择时间',
        body = _getTimeBody();
    
    _rander(_getHead(title), _getBody(body));    
  }
  function _getHead(title) {
    var head = 
    '<span class="date-before">' + 
      ( mydate.opt.type !== 'time' ? '<i class="fa fa-angle-double-left"></i>' : '' ) + 
      ( mydate.opt.type == 'date' ? '<i class="fa fa-angle-left"></i>' : '' ) + 
    '</span>' +
    '<span class="date-year-month">' + title + '</span>' +  
    '<span class="date-after">' + 
      ( mydate.opt.type == 'date' ? '<i class="fa fa-angle-right"></i>' : '' ) + 
      ( mydate.opt.type !== 'time' ? '<i class="fa fa-angle-double-right"></i>' : '' ) + 
    '</span>';

    return head;
  }

  function _getBody(content) {
    var body;
    if(mydate.opt.type !== 'time') {
      var thead = 
      '<thead><tr><th>日</th><th>一</th><th>二</th><th>三</th>' + 
      '<th>四</th><th>五</th><th>六</th></tr></thead>',
      body = 
      '<table>' +
        ( mydate.opt.type == 'date' ? thead : '') + 
        '<tbody>' + content + '</tbody>' + 
      '</table>';
    } else {
      body = content; 
    }

    return body;
  } 
  
  function _getYearBody() {
    var years = '';
    
    for(var i = 0; i < MAX_YEAR_COUNT; i++) {
      years += '<td>' + (selectYear - 7 + i) + '年</td>'; 
      if(i % RAW_YEAR_COUNT == RAW_YEAR_COUNT -1 && i !== MAX_YEAR_COUNT - 1) {
        years += '</tr><tr>';
      } 
    }
  
    return '<tr>' + years + '</tr>';
  }
  function _getDateBody() {
    var dateContent = _getDateContent();
    var dates = '';
  
    for(var i = 0; i < MAX_DATE_COUNT; i++) {
      dates += dateContent[i];
      if(i % RAW_DATE_COUNT == RAW_DATE_COUNT - 1 && i !== MAX_DATE_COUNT - 1){
        dates += '</tr><tr>'
      } 
    }

    return '<tr>' + dates + '</tr>';
  }

  function _getMonthBody() {
    var months = '';

    for(var i = 0; i < MAX_MONTH_COUNT; i++) {
      months += '<td>' + (i + 1) + '</td>';
      if(i % RAW_MONTH_COUNT == RAW_MONTH_COUNT - 1 && i !== MAX_MONTH_COUNT - 1) {
        months += '</tr><tr>';
      }
    }
    
    return '<tr>' + months + '</tr>';
  }

  function _getTimeBody() {
    var time = 
    '<div>' + 
      '<div class="time-head">' + 
        '<span>时</span><span>分</span><span>秒</span>' + 
      '</div>' + 
      '<div class="time-body">' + 
        '<ul>' + _getTimes(24) + '</ul>' + 
        '<ul>' + _getTimes(60) + '</ul>' + 
        '<ul>' + _getTimes(60) + '</ul>' + 
      '</div>' 
    '</div>';
    
    return time;

    function _getTimes(times) {
      var lis = '';
      
      for(var i = 0; i < times; i++) {
       lis += '<li>' + i + '</li>';  
      }
      return lis;
    }
  }  
  function _rander(head, body) {
    var content =  
      '<div class="date-header">' + head + '</div>' + 
      '<div class="date-body">' + body + '</div>' + 
      '<div class="date-footer">' + 
        '<button class="date-clear">清空</button> ' + 
        '<button class="date-now">现在</button> ' + 
        '<button class="date-select">确定</button>' +  
      '</div>';  
  
    mydate.dateDiv.innerHTML = content; 
  }
  
  /** 显示每个月所有日期 */
  function _getDateContent() {
    var monthDates = [],
        now = new Date(),
        currentDate = now.getDate(),
        monthFirstDate = new Date(selectYear, selectMonth),
        nthDay = monthFirstDate.getDay(),
        monthCount = _getAllMonthDates(selectYear),
        preMonthCount = monthCount[selectMonth - 1]
        currentMonthCount = monthCount[selectMonth],
        nextMonthCount = monthCount[selectMonth + 1];
  
    for(var i = nthDay - 1 ; i >= 0; i--) {
      monthDates.push('<td class="no-date-of-current-month">' + 
      (preMonthCount - i) + '</td>');
    }
  
    for(var i = 1; i <= currentMonthCount; i++) {
      if(currentDate == i) {
        monthDates.push('<td class="date-current" >' + i + '</td>');
      } else {
        monthDates.push('<td class="" >' + i + '</td>');
      }
    }
  
    var len = MAX_DATE_COUNT - monthDates.length;
    for(var i = 1; i <= len; i++) {
      monthDates.push('<td class="no-date-of-current-month">' + i + '</td>');
    }
  
    return monthDates;
  }
  
   /** 每年各月有多少天 */
  function _getAllMonthDates(year) {
    var month = {},
        firstDateOfMonth,
        minDayCount; 
    for(var i = 0; i < 12; i++) {
      minDayCount = 28;
      firstDateOfMonth = new Date(year, i);
      for(var j = 29; j < 32; j++) {
        // 一天86400000秒秒
        if((new Date(firstDateOfMonth.getTime() - 1 + j * 86400000).getMonth()) 
          !== i) {
          break;
        }
        minDayCount++;
      }
      month[i] = minDayCount;
    }
    return month;
  }
};


// 设置样式的通用方法
function setStyle(ele, style) {
  if(ele) {
    for(var s1 in style) {
      ele.style[s1] = style[s1];
    }
  }
}